/*
 * @Author: xinqiao lxq1990.0716@qq.com
 * @Date: 2023-12-14 14:14:41
 * @LastEditors: xinqiao lxq1990.0716@qq.com
 * @LastEditTime: 2024-01-11 16:49:11
 * @FilePath: \partal\src\config\menu\modules\component.ts
 * @Description: 组件-菜单
 */

import { PLANTTYPE_ENUM } from '@/enum/globalEnum'
import { toCamelCase } from '@/utils/common'
import { getCamelChars } from '@/utils/pinyin'
import { requestGet } from '@/utils/request'

/**
 * 转换菜单（子工程菜单 -> 主工程菜单）
 * @param plant 子工程类型
 * @returns 
 */
const convertMenu = async (plant: PLANTTYPE_ENUM) => {
  const menus: any = await requestGet({ url: `/${plant}/list.json?${new Date().getTime()}` }).catch((e) => {})
  if (!menus || typeof(menus) === 'string') return []
  return menus.map((third: IChildComponentMenu) => {
    const thirdPath = getCamelChars(third.text)
    return {
      text: third.text,
      name: `${plant}-${thirdPath}`,
      path: thirdPath,
      children: (third.children as IChildComponentMenu[]).map((forth: IChildComponentMenu) => {
        const routers = forth.direct?.split('/') as string[]
        const forthPath = routers[routers.length - 1]
        return {
          text: `${forth.text} ${toCamelCase(forthPath)}`,
          name: `${plant}-${thirdPath}-${forthPath}`,
          path: forthPath,
          fullPath: `/component/${plant}/${thirdPath}/${forthPath}`,
          component: () => import('@/views/component/sandbox.vue'),
          checked: false,
          meta: { direct: forth.direct }
        }
      })
    }
  })
}

/** 一级组件菜单 */
const firstComponent = {
  text: '组件',
  name: 'component',
  path: '/component',
  component: () => import('@/layout/layoutMenu.vue'),
  isMenu: true,
  expanded: false
}

/** 二级组件菜单 */
const secondComponent = (plant: PLANTTYPE_ENUM) => ({
  text: plant,
  name: plant,
  path: plant
})

/** 单个组件 */
export const getComponent = async (plantType: PLANTTYPE_ENUM) => ({
  ...firstComponent,
  children: [{
    ...secondComponent(plantType),
    children: await convertMenu(plantType)
  }]
})

/** 所有组件 */
export const getAllComponent = async () => {
  const pcComponent = await convertMenu(PLANTTYPE_ENUM.PC)
  const appComponent = await convertMenu(PLANTTYPE_ENUM.APP)
  const xcxComponent = await convertMenu(PLANTTYPE_ENUM.XCX)
  const h5Component = await convertMenu(PLANTTYPE_ENUM.H5)
  return {
    ...firstComponent,
    children: [
      { ...secondComponent(PLANTTYPE_ENUM.PC), children: pcComponent },
      { ...secondComponent(PLANTTYPE_ENUM.APP), children: appComponent },
      { ...secondComponent(PLANTTYPE_ENUM.XCX), children: xcxComponent },
      { ...secondComponent(PLANTTYPE_ENUM.H5), children: h5Component }
    ]
  }
}
